using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Ploeh.AutoFixture;
using System.IO;
using FileDownloadServer;
using ArtOfTest.WebAii.Core;
using ArtOfTest.WebAii.Win32.Dialogs;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UITesting;
using Tests.Properties;
using System.Web.Http;
using Microsoft.VisualStudio.TestTools.UnitTesting.Web;
using System.Linq;
using FluentAssertions;
using ArtOfTest.Common.Win32;
using System.Diagnostics;

namespace Tests
{
	class WebApplication : IDisposable
	{
		private readonly Process webServer;

		public WebApplication(Process webServer, Uri address)
		{
			this.webServer = webServer;
			this.Address = address;
		}

		public void Stop()
		{
			if (webServer.HasExited)
				CheckForErrors();
			else
				webServer.Kill();
		}

		private void CheckForErrors()
		{
			var errorOutput = webServer.StandardError.ReadToEnd();
			if (errorOutput.Any())
				throw new Exception("Web server produced errors: " + errorOutput);

			var exitCode = webServer.ExitCode;
			if (exitCode != 0)
				throw new Exception("Web server produced error code: " + exitCode);
		}

		public void Dispose()
		{
			Stop();
			webServer.Dispose();
		}

		public Uri Address { get; private set; }
	}
}
